﻿using OpenHardwareMonitor.Hardware;
using System;
using System.Linq;

namespace TrayCpu
{
    internal class DataMonitor : IDisposable
    {
        private Computer computer;
        private IHardware hardware;
        private bool isDisposed;

        public DataMonitor()
        {
            computer = new OpenHardwareMonitor.Hardware.Computer();
            computer.CPUEnabled = true;
            computer.Open();
            hardware = computer.Hardware.FirstOrDefault(x => x.HardwareType == HardwareType.CPU);
        }

        public void Dispose()
        {
            isDisposed = true;
            computer.Close();
        }

        public (float?, float?) GetData()
        {
            if(isDisposed)
            {
                return (null, null);
            }
            float? temperature = null;
            float? cpuUsage = null;

            try
            {
                hardware.Update();
                // 遍历所有硬件，找到 CPU 温度传感器
                if(hardware.HardwareType == HardwareType.CPU)
                {
                    temperature = hardware.Sensors.FirstOrDefault(x => x.SensorType == OpenHardwareMonitor.Hardware.SensorType.Temperature && x.Name.Contains("CPU Package"))?.Value;
                    cpuUsage = hardware.Sensors.FirstOrDefault(x => x.SensorType == OpenHardwareMonitor.Hardware.SensorType.Load && x.Name.Contains("CPU Total"))?.Value;
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("刷新硬件信息时出错: " + ex.Message);
            }

            return (temperature, cpuUsage);
        }
    }
}